/**
 * 数据库连接管理
 * Database Connection Management
 */

const mysql = require('mysql2/promise');
const config = require('../config/config');
const logger = require('../utils/logger');

class DatabaseConnection {
  constructor() {
    this.pool = null;
    this.isConnected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectDelay = 5000; // 5秒
  }

  /**
   * 初始化数据库连接池
   */
  async initialize() {
    try {
      this.pool = mysql.createPool({
        host: config.database.host,
        port: config.database.port,
        user: config.database.user,
        password: config.database.password,
        database: config.database.database,
        connectionLimit: config.database.connectionLimit || 10,
        charset: 'utf8mb4',
        timezone: '+08:00',
        // 连接池优化配置
        queueLimit: config.database.queueLimit || 0,
        idleTimeout: config.database.idleTimeout || 300000,
        // 性能优化配置
        multipleStatements: config.database.multipleStatements || false,
        dateStrings: config.database.dateStrings || false,
        supportBigNumbers: config.database.supportBigNumbers || true,
        bigNumberStrings: config.database.bigNumberStrings || false,
        // SSL配置（如果需要）
        ssl: false
      });

      // 测试连接
      await this.testConnection();
      
      this.isConnected = true;
      this.reconnectAttempts = 0;
      
      logger.info('数据库连接池初始化成功 / Database connection pool initialized successfully');
      
      // 监听连接池事件
      this.setupEventListeners();
      
    } catch (error) {
      logger.error('数据库连接池初始化失败 / Database connection pool initialization failed', {
        error: error.message,
        stack: error.stack
      });
      
      // 尝试重连
      await this.handleReconnect();
    }
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    if (!this.pool) return;

    this.pool.on('connection', (connection) => {
      logger.debug(`新的数据库连接建立 / New database connection established: ${connection.threadId}`);
    });

    this.pool.on('error', (error) => {
      logger.error('数据库连接池错误 / Database connection pool error', {
        error: error.message,
        code: error.code
      });

      if (error.code === 'PROTOCOL_CONNECTION_LOST' || error.code === 'ECONNREFUSED') {
        this.isConnected = false;
        this.handleReconnect();
      }
    });
  }

  /**
   * 测试数据库连接
   */
  async testConnection() {
    if (!this.pool) {
      throw new Error('数据库连接池未初始化 / Database connection pool not initialized');
    }

    const connection = await this.pool.getConnection();
    try {
      await connection.execute('SELECT 1');
      logger.debug('数据库连接测试成功 / Database connection test successful');
    } finally {
      connection.release();
    }
  }

  /**
   * 处理重连
   */
  async handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      logger.error('数据库重连次数超过限制，停止重连 / Database reconnection attempts exceeded limit');
      return;
    }

    this.reconnectAttempts++;
    logger.info(`尝试重连数据库 (${this.reconnectAttempts}/${this.maxReconnectAttempts}) / Attempting to reconnect database`);

    setTimeout(async () => {
      try {
        await this.initialize();
      } catch (error) {
        logger.error('数据库重连失败 / Database reconnection failed', {
          error: error.message,
          attempt: this.reconnectAttempts
        });
      }
    }, this.reconnectDelay);
  }

  /**
   * 获取数据库连接
   */
  async getConnection() {
    if (!this.pool || !this.isConnected) {
      throw new Error('数据库连接不可用 / Database connection not available');
    }

    try {
      return await this.pool.getConnection();
    } catch (error) {
      logger.error('获取数据库连接失败 / Failed to get database connection', {
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 执行查询
   */
  async query(sql, params = []) {
    const startTime = Date.now();
    const connection = await this.getConnection();
    
    try {
      const [rows, fields] = await connection.execute(sql, params);
      const queryTime = Date.now() - startTime;
      
      // 记录性能指标
      this.recordQueryMetrics(sql, queryTime);
      
      // 对于INSERT操作，返回insertId
      if (sql.trim().toUpperCase().startsWith('INSERT')) {
        return { rows: { insertId: rows.insertId, affectedRows: rows.affectedRows }, fields };
      }
      
      // 对于UPDATE/DELETE操作，返回affectedRows
      if (sql.trim().toUpperCase().startsWith('UPDATE') || sql.trim().toUpperCase().startsWith('DELETE')) {
        return { rows: { affectedRows: rows.affectedRows }, fields };
      }
      
      // 对于SELECT操作，返回数据行
      return { rows, fields };
    } catch (error) {
      logger.error('数据库查询失败 / Database query failed', {
        sql: sql.substring(0, 100) + '...',
        error: error.message,
        queryTime: Date.now() - startTime
      });
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 记录查询性能指标
   */
  recordQueryMetrics(sql, queryTime) {
    const config = require('../config/config');
    
    // 检查是否为慢查询
    const isSlowQuery = queryTime > (config.performance?.slowQueryThreshold || 1000);
    
    if (isSlowQuery) {
      logger.warn('慢查询检测 / Slow query detected', {
        sql: sql.substring(0, 200) + '...',
        queryTime: queryTime + 'ms',
        threshold: config.performance?.slowQueryThreshold || 1000
      });
    }

    // 如果性能监控模块可用，记录指标
    try {
      const { performanceMonitor } = require('../utils/performance');
      performanceMonitor.recordDatabaseQuery(queryTime, isSlowQuery);
      performanceMonitor.updateDatabaseConnections(this.getPoolStatus().activeConnections);
    } catch (error) {
      // 忽略性能监控错误，不影响主要功能
    }
  }

  /**
   * 执行事务
   */
  async transaction(callback) {
    const connection = await this.getConnection();
    
    try {
      await connection.beginTransaction();
      
      const result = await callback(connection);
      
      await connection.commit();
      return result;
      
    } catch (error) {
      await connection.rollback();
      logger.error('数据库事务失败 / Database transaction failed', {
        error: error.message
      });
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 获取连接池状态
   */
  getPoolStatus() {
    if (!this.pool) {
      return {
        connected: false,
        totalConnections: 0,
        activeConnections: 0,
        idleConnections: 0
      };
    }

    return {
      connected: this.isConnected,
      totalConnections: this.pool._allConnections?.length || 0,
      activeConnections: this.pool._acquiringConnections?.length || 0,
      idleConnections: this.pool._freeConnections?.length || 0,
      queuedRequests: this.pool._connectionQueue?.length || 0
    };
  }

  /**
   * 关闭连接池
   */
  async close() {
    if (this.pool) {
      try {
        await this.pool.end();
        this.isConnected = false;
        logger.info('数据库连接池已关闭 / Database connection pool closed');
      } catch (error) {
        logger.error('关闭数据库连接池失败 / Failed to close database connection pool', {
          error: error.message
        });
      }
    }
  }
}

// 创建全局数据库连接实例
const db = new DatabaseConnection();

// 导出数据库连接实例和便捷方法
module.exports = {
  db,
  
  // 便捷方法
  async query(sql, params) {
    return await db.query(sql, params);
  },
  
  async transaction(callback) {
    return await db.transaction(callback);
  },
  
  async getConnection() {
    return await db.getConnection();
  },
  
  getStatus() {
    return db.getPoolStatus();
  },
  
  async initialize() {
    return await db.initialize();
  },
  
  async close() {
    return await db.close();
  }
};